<script lang="ts">
import {Vue, Component, Prop, Watch, Provide, Emit} from 'vue-property-decorator';
import ToolBar from "./plugins/ToolBar.vue";
import {
  AuditRequestFields,
  BusinessType,
  BusinessTypeEnum,
  CommodityAuditRequestDto,
  MasterModalProps,
  pluginType
} from "./type";
import EventBus from "./eventBus/event";
import ModalContent from "./lib/ModalContent/ModalContent.vue";
import InfoPreview  from "./lib/MainDisplay/InfoPreview.vue";
import AuditInfo from "./lib/MainDisplay/AuditInfo.vue";
import DataMatch from "./lib/DataMatch/DataMatch.vue";
import {auditType} from "./lib/ModalContent/types";
import masterModal from "../../api/module/masterModal";
import {
  CommodityDetail,
  CommodityDetailDto,
  CommodityLicenseDetail,
  CommodityReviewItem,
  CommonResult, LicenseDetailDto
} from "./plugins/dto";
import {CommonPageRequest, CommonPageResponse, ParamDto} from "../../utils/types";
import {OptionType} from "./lib/Base/CommodityClassify/type";
@Component({
  name: 'MasterDataModal',
  components: {DataMatch, AuditInfo, ModalContent, ToolBar, InfoPreview}
})
export default class MasterModal extends Vue implements MasterModalProps{
  @Prop({type: String, default: "", required: false})title!: string;
  @Prop({type: String, required: false})id!: string;
  @Prop({type: String, default: "md"})size!: "sm" | "md" | "lg";
  @Prop({type: Boolean, default: false})visible!: boolean;
  @Prop({type: Boolean, default: true})destroyOnClose!: boolean;
  @Prop({type: Boolean, default: false})closeOnClickModal!: boolean;
  @Prop({type: Boolean, default: false})closeOnPressEscape!: boolean;
  @Prop({type:String, default: ""})businessType!:BusinessTypeEnum;
  @Prop({type: Array, default: ()=>[{}]})plugins!: pluginType[];
  @Prop({type:String, default:"add"})modalType!: auditType;
  @Prop({type:Number, default: 1})currentPage!:number;
  @Prop({type:Number, default: 0})statusFlag!:number;  // 区别是否匹配还是审核
  @Prop({type:String, default: ""})mode!: string;  // 模式： preview代表预览
  @Prop({type:Boolean, default: true})showAuditTool!: boolean;  // 是否展示审核栏
  private _innerSize:string = ""
  private modal_visible:boolean = false;
  refresh:boolean =false;
  submitFormData:CommodityReviewItem = {} as any
  loading:boolean = false;
  private innerBusinessType:any = Vue.observable({businessType: ""})
  private auditType:any = Vue.observable({auditType: "add"})
  private modeType:any = Vue.observable({mode: ""})
  // 审批商品详情数据
  private providedCommodityDetail:any = Vue.observable({
    "articleNo": "",
    "brandId": 0,
    "brandName": "",
    "brandStandardCode": "",
    "cnName": "",
    "commodityType": 0,
    "commodityTypeName": "",
    "createdTime": "",
    "licenses": [],
    "managementCategory": "",
    "minSaleUnit": "",
    "minSaleUnitName": "",
    "packageParam": "",
    "specification": "",
    "standardCode": "",
    "tagPicture": ""
  })
  // 审批品牌详情数据
  private providedBrandDetail:any = Vue.observable({
    cnName: "",
    commodityPicture: "",
    companyName: "",
    enName: "",
    logo: ""
  })
  // 审批商品证照数据
  private providedCommodityLicenseDetail:any = Vue.observable({
    "agentAddress": "",
    "agentName": "",
    "annex": "",
    "applyType": 0,
    "approvalDate": "",
    "approvalDepartment": "",
    "auditTime": "",
    "auditUserId": 0,
    "changes": "",
    "comment": "",
    "storageConditions": "",
    "createdTime": "",
    "createdUserId": 0,
    "effDate": "",
    "expectPurpose": "",
    "flagBit": 0,
    "id": 0,
    "licenseAddress": "",
    "licenseCode": "",
    "licenseName": "",
    "licenseType": 0,
    "managementCategory": "",
    "mdResult": 0,
    "otherContents": "",
    "periodValidity": "",
    "picture": "",
    "productDescription": "",
    "productName": "",
    "productionAddress": "",
    "serialNo": "",
    "source": "",
    "sourceDataId": "",
    "sourceDataNo": "",
    "sourceTenantId": "",
    "sourceTenantName": "",
    "specification": "",
    "specificationInAnnex": "",
    "standardCode": "",
    "status": 0,
    "updatedTime": "",
    "updatedUserId": 0,
    "usCreditCode": ""
  })
  // 审批合作商证照数据
  private providedPartnerLicenseDetail:any = Vue.observable({
    "applyType": 0,
    "auditTime": "",
    "auditUserId": 0,
    "businessDateStart": "",
    "businessPremises": "",
    "businessRecordCertificate": "",
    "businessScope": "",
    "companyName": "",
    "companyType": "",
    "createdTime": "",
    "createdUserId": 0,
    "dateOfIncorporation": "",
    "diagnosisSubject": "",
    "entPrincipal": "",
    "filingDate": "",
    "filingDepartment": "",
    "flagBit": 0,
    "id": 0,
    "legalPerson": "",
    "licenseCode": "",
    "licenseHandleDate": "",
    "licenseName": "",
    "licenseType": 0,
    "mark": "",
    "mdResult": 0,
    "modeOfOperation": "",
    "nature": 0,
    "organizer": "",
    "productRegistrationForm": "",
    "qualityManageName": "",
    "warehouseAddress": "",
    "serialNo": "",
    "source": "",
    "sourceDataId": "",
    "sourceDataNo": "",
    "sourceOfFunds": "",
    "sourceTenantId": "",
    "sourceTenantName": "",
    "standardCode": "",
    "startUpFunds": "",
    "status": 0,
    "uniqueCheckCode": "",
    "unitLicensePicture": "",
    "updateTime": "",
    "updatedTime": "",
    "updatedUserId": 0,
    "usCreditCode": "",
    "validityPeriod": "",
    "websiteDomainName": ""
  })
  private provideApplyInfo:any = Vue.observable({sourceTenantName: "",
      createdTime: "",
      remark: ""})
  private provideStandardInfo: any = Vue.observable({
    "articleNo": "",
    "brandId": 0,
    "brandName": "",
    "brandStandardCode": "",
    "cnName": "",
    "commodityType": 0,
    "commodityTypeName": "",
    "createdTime": "",
    "licenses": [],
    "managementCategory": "",
    "minSaleUnit": "",
    "minSaleUnitName": "",
    "packageParam": "",
    "specification": "",
    "standardCode": "",
    "tagPicture": ""
  })
  // 编辑页面初始化数据
  newFieldsList = []
  auditedFieldsList = []
  inner_currentPage:number = 1;
  filesList = [
    {
      name: "标准商品编码",
      key: "commodityCode",
      value: "commodity"
    },
    {
      name: "商品名称",
      key: "commodityName",
      value: ""
    },
    {
      name: "规格型号",
      key: "specication",
      value: ""
    },
    {
      name: "品牌",
      key: "brand",
      value: ""
    },
    {
      name: "基本单位",
      key: "unit",
      value: "commodity"
    },
    {
      name: "包装参数",
      key: "params",
      value: "1个/袋"
    },
    {
      name: "证照编号",
      key: "registration",
      value: "湘长械备20221697号"
    }
  ]
  private $message: any;

  @Emit("visibleChange")
  onVisibleEmit(value:boolean){
    return value
  }
  @Watch("size")
  onSizeChange(newSize: string) {
    this._innerSize = newSize
  }
  @Watch("modalType", {immediate: true})
  onModalTypeChange(value: string) {
    this.auditType.auditType = value
  }

  @Watch("mode", {immediate: true})
  onModeTypeChange(value: string) {
    this.modeType.mode = value
  }
  
  @Watch("businessType", {immediate: true})
  onbusinessTypeChange(value: BusinessTypeEnum) {
    this.innerBusinessType.businessType = value
  }

  @Watch("id", {immediate: true})
  onIdChange(newId: string) {
    if(newId){
      this.id = newId
    }
  }

  @Watch("statusFlag", {immediate: true})
  onStatusFlagChange(value: number) {
    if(value === 2){
      this.auditType.auditType = 'match'
    }
  }

  @Provide("showAuditTool")
  providedShowAuditTool = this.showAuditTool;


  @Provide("auditType")
  get providedAuditType(){
    return this.auditType
  }
  set providedAuditType(value) {
    this.auditType = value;
  }

  @Provide("modeType")
  get providedModeType(){
    return this.modeType
  }
  set providedModeType(value) {
    this.modeType = value;
  }

  @Watch("currentPage")
  onCurrentPageChange(currentPage:number) {
    this.inner_currentPage = currentPage
  }
  @Emit("update:visible")
  visibleChange(value: boolean) {
    return value
  }
  destroyed(){
    EventBus.$off("plugin_event_pre")
    EventBus.$off("plugin_event_next")
    EventBus.$off("plugin_event_diff")
    EventBus.$off("submitAudit")
  }
  async getDetailData(operate:string, type:string, afterGet?:"close"){
      const requestParams:any= {
        id: this.id,
        operate: operate,
        statusFlag: 0
      }
      this.loading = true
      let res:CommonResult<{id:number}>;
      let detail:CommonResult<CommodityDetailDto | LicenseDetailDto>;
      if(type === 'jump'){
        res =  this.statusFlag === 0 ? await masterModal.getReviewList(requestParams, this.innerBusinessType.businessType) : await masterModal.getMatchList(requestParams, this.innerBusinessType.businessType)
        if(res!.data && !res!.data.id){
          this.loading =false
          if(afterGet === "close"){
            this.$message.warning("当前已经是最后一条，已自动为您关闭窗口")
            this.close()
          }else{
            this.$message.warning("没有数据")
          }
          return
        }
        const id = res.data!.id
        this.id = id.toString()
        this.refresh = true
        detail = await masterModal.getCommodityDetail(id!.toString(), this.innerBusinessType.businessType)
        this.refresh = false
      }else{
        this.refresh = true
        detail = await masterModal.getCommodityMasterDetail(this.id, this.innerBusinessType.businessType)
        this.refresh = false
      }
      this.loading = false
      this.$nextTick(()=>{
          if(detail.code === 200 && detail.data && detail.data.applyData){
            if(this.statusFlag === 2){
              this.auditType.auditType = 'match'
            }else{
              if (detail.data.applyInfo) this.auditType.auditType = detail.data.applyInfo.applyType === 1 ? "add" : "edit"
              else this.auditType.auditType = 'add' 
            }
            this.$nextTick(()=>{
              setTimeout(()=>{
                if(this.innerBusinessType.businessType === "commodity"){
                  for(const key in detail.data.applyData){
                    (this.providedCommodityDetail as any)[key] = detail.data.applyData[key as keyof typeof detail.data.applyData];
                  }
                }else if(this.innerBusinessType.businessType === "brand"){
                  for(const key in detail.data.applyData){
                    (this.providedBrandDetail as any)[key] = detail.data.applyData[key as keyof typeof detail.data.applyData]
                  }
                }else if(["commodityLicense", "foreignLicense" , "domesticRecord" , "foreignRecord"].includes(this.innerBusinessType.businessType)){
                  
                  for(const key in detail.data.applyData){
                    (this.providedCommodityLicenseDetail as any)[key] = detail.data.applyData[key as keyof typeof  detail.data.applyData]
                  }
                  console.log("-------------------------", this.innerBusinessType.businessType, this.providedCommodityLicenseDetail)
                  
                }else if(this.innerBusinessType.businessType === "partnerLicense"){
                  for(const key in detail.data.applyData){
                    (this.providedPartnerLicenseDetail as any)[key] = detail.data.applyData[key as keyof typeof  detail.data.applyData]
                  }
                }
                for(const key in detail.data.applyInfo || {}){
                  (this.provideApplyInfo as any)[key] = detail.data.applyInfo[key as keyof typeof detail.data.applyInfo]
                }
                for(const key in detail.data.standardData || {}){
                  (this.provideStandardInfo as any)[key] = detail.data.standardData[key as keyof typeof detail.data.standardData]
                }
              }, 200)
            })
          }

      })

  }

  @Watch("visible", {immediate: true})
  async onVisibleChange(newVisible: boolean) {
    this.modal_visible = newVisible
    if(newVisible){
      this.loading = true
      this.refresh = false
      // 获取详情信息
      await this.getDetailData("detail", "detail")
      this.loading = false
      EventBus.$on("plugin_event_pre", ()=>{
        this.getDetailData("pre", "jump")}
      )
      EventBus.$on("plugin_event_next", (data:any)=>{
        console.log("======>5")
        this.getDetailData("next", "jump", data)
      })
      EventBus.$on("plugin_event_diff", ()=>{})
      EventBus.$on("closeModal", ()=>{this.close()})
      EventBus.$on("submitAudit", async ()=> {
        let data: any = {}
        let displayData: any = {}
        if (this.auditType.auditType !== 'match') {
          displayData = (this.$refs["modalContent"] as any)['getDisplayData']()
          data = (this.$refs["modalContent"] as any)['checkContentData'] as AuditRequestFields
        } else {
          const key:string = this.innerBusinessType.businessType === "commodity" ?
              "providedCommodityDetail" : this.innerBusinessType.businessType === "brand" ?
                  "providedBrandDetail" : ["commodityLicense", "foreignLicense" , "domesticRecord" , "foreignRecord"].includes(this.innerBusinessType.businessType) ?
                      "providedCommodityLicenseDetail" :
                      "providedPartnerLicenseDetail"
          displayData = (this.$refs["modalContent"] as any)[key]
          data = ((this.$refs["modalContent"] as any)['getMatchData'] as Function)(key)
        }
        if(["commodityLicense", "foreignLicense" , "domesticRecord" , "foreignRecord"].includes(this.innerBusinessType.businessType)){
          delete data.managementCategory
        }
        console.log("提交数据===>displayData", displayData, "data===>", data)
        const requestData: CommodityAuditRequestDto = Object.assign(displayData, data, {id: this.id})
        requestData.licenseStandardCode = displayData.licenseCode
        requestData.tags = data.tags
        delete requestData.standardCode
        const res: CommonResult<any> = this.auditType.auditType !== 'match' ? await masterModal.auditCommodity(requestData, this.innerBusinessType.businessType) : await masterModal.auditMatchCommodity(requestData, this.innerBusinessType.businessType)
        if (res.code === 200) {
          this.$message.success("审核成功")
          this.refresh = true
          this.$forceUpdate();
          setTimeout(() => {
            this.refresh = false;
            EventBus.$emit("plugin_event_next", "close")
          })
        } else {
          this.$message.warning(res.msg)
        }
        EventBus.$on("cancelAudit", () => {
          this.close()
        })
      })
    }else{
      EventBus.$off("plugin_event_pre")
      EventBus.$off("plugin_event_next")
      EventBus.$off("plugin_event_diff")
      EventBus.$off("submitAudit")
    }
  }


  @Provide("plugins")
  providedPlugins = this.plugins.map(i => {i.$root = this; return i})
  created() {
    this._innerSize = this.size;
  }

  @Provide("businessType")
  providedBusinessType = this.innerBusinessType;

  @Provide("auditedFields")
  providedAuditedFields = this.auditedFieldsList

  @Provide("newFields")
  providedNewFields = this.newFieldsList

  @Provide("CommodityDetail")
  get provideCommodityDetail() {
    return this.providedCommodityDetail;
  }

  @Provide("BrandDetail")
  get provideBrandDetail(){
    return this.providedBrandDetail
  }


  @Provide("CommodityLicenseDetail")
  get provideCommodityLicenseDetail(){
    return this.providedCommodityLicenseDetail;
  }

  @Provide("PartnerLicenseDetail")
  get providePartnerLicenseDetail(){
    return this.providedPartnerLicenseDetail;
  }

  @Provide("ApplyInfo")
  get providedApplyInfo(){
    return this.provideApplyInfo
  }

  @Provide("StandardInfo")
  get providedStandardInfo(){
    return this.provideStandardInfo
  }

  mounted() {

  }

  close(){
    this.modal_visible = false;
    this.onVisibleEmit(false)
    this.refresh = true;
    (this.$refs["modalContent"] as any).$destroy();
    this.visibleChange(false)
    if(window.MasterModalInstance.length){
      window.MasterModalInstance.forEach( item => {
        item.$destroy();
        if (item.$el.parentNode) {
          item.$el.parentNode.removeChild(item.$el);
        }
      })
    }
  }

}
</script>

<template>
<div>
   <el-dialog
       :visible="modal_visible"
       :title="title"
       @close="close"
       :custom-class="`${_innerSize}-modal`"
       :destroy-on-close="true"
       :close-on-click-modal="closeOnClickModal"
       :close-on-press-escape="closeOnPressEscape"
       v-loading="loading"
   >
      <div slot="title" class="cc-modal-title">
        {{title}}
      </div>
     <!-- <ToolBar/> -->
     <ModalContent ref="modalContent" v-if="!refresh">
     </ModalContent>
   </el-dialog>
</div>
</template>

<style scoped lang="scss">
::v-deep .el-dialog__wrapper{
  display: flex;
  align-content: center;
  flex-wrap: wrap;
  .el-dialog__header{
    padding: 10px 15px;
    .cc-modal-title{
      text-align: left;
    }
  }
  .el-dialog__body{
    padding: 0px !important;
    height: calc(100% - 42px);
  }
  .el-dialog__headerbtn{
    top: 15px !important;
  }
}

@mixin responsive-class($name){
  ::v-deep .md-#{$name}{
    width: 70%;
    margin: auto!important;
    aspect-ratio: 16/8;
  }
  ::v-deep .lg-#{$name}{
    width: 90%;
    margin: auto!important;
    aspect-ratio: 16/8;
  }
  ::v-deep .sm-#{$name}{
    width: 60%;
    margin: auto!important;
    aspect-ratio: 16/8;
  }

}

@include responsive-class(modal);
</style>